<template>
  <div class="user-forum">
    <!-- 操作区域 -->
    <el-card class="action-area">
      <el-row :gutter="20" type="flex" justify="space-between" align="middle">
        <el-col :span="16">
          <el-input
            v-model="queryParams.title"
            placeholder="搜索帖子"
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="8" style="text-align: right">
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>发布帖子
          </el-button>
          <el-button @click="getList">
            <el-icon><Refresh /></el-icon>刷新列表
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 帖子列表 -->
    <el-card v-loading="loading" class="post-list">
      <template v-if="postList.length">
        <div v-for="post in postList" :key="post.postId" class="post-item">
          <el-card shadow="hover">
            <div class="post-header">
              <div class="user-info">
                <el-avatar 
                  :size="40" 
                  :src="getAvatarUrl(post.avatar)"
                ></el-avatar>
                <div class="info-text">
                  <span class="username">{{ post.userName || '未知用户' }}</span>
                  <span class="time">{{ post.createTime }}</span>
                </div>
              </div>
              <div class="post-stats">
                <el-tag size="small">{{ post.categoryName }}</el-tag>
                <span class="stat-item">
                  <el-icon><View /></el-icon>
                  {{ post.viewCount || 0 }}
                </span>
                <span class="stat-item">
                  <el-icon><ChatDotRound /></el-icon>
                  {{ post.commentCount || 0 }}
                </span>
                <el-button
                  v-if="userId && post.userId === userId"
                  type="primary"
                  link
                  @click.stop="handleEdit(post.postId)"
                >
                  编辑
                </el-button>
              </div>
            </div>
            <div class="post-content" @click="viewDetail(post.postId)">
              <h3 class="post-title">
                <router-link
                  :to="`/user/forum/post/${post.postId}`"
                  class="post-title-link"
                >
                  {{ post.title }}
                </router-link>
              </h3>
              <p class="post-summary">{{ post.content }}</p>
              <div v-if="post.images" class="post-images">
                <el-image
                  v-for="(image, index) in parseImages(post.images)"
                  :key="index"
                  :src="image"
                  :preview-src-list="parseImages(post.images)"
                  fit="cover"
                  class="preview-image"
                />
              </div>
            </div>
          </el-card>
        </div>
      </template>
      <el-empty v-else description="暂无帖子" />
    </el-card>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 30, 40]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 发帖对话框 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="600px"
      append-to-body
      @close="resetForm"
    >
      <el-form
        ref="postForm"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入帖子标题" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择帖子分类">
            <el-option
              v-for="item in categoryOptions"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入帖子内容"
          />
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
            v-model:file-list="fileList"
            :action="uploadImgUrl"
            list-type="picture-card"
            :headers="headers"
            :before-upload="beforeUpload"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            multiple
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, Search, View, ChatDotRound, Refresh } from '@element-plus/icons-vue'
import { listCategory } from '@/api/ich/category'
import { listPost, addPost, getPost, updatePost } from '@/api/ich/forum'
import { getToken } from '@/utils/auth'
import useUserStore from '@/store/modules/user'

const router = useRouter()
const userStore = useUserStore()
const userId = ref(null)
const loading = ref(false)
const total = ref(0)
const postList = ref([])
const categoryOptions = ref([])
const fileList = ref([])

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  title: undefined,
  categoryId: undefined
})

// 表单参数
const form = ref({
  postId: undefined,
  title: undefined,
  categoryId: undefined,
  content: undefined,
  images: []
})

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '标题不能为空', trigger: 'blur' },
    { min: 2, max: 50, message: '标题长度必须在2到50个字符之间', trigger: 'blur' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '内容不能为空', trigger: 'blur' },
    { min: 10, max: 2000, message: '内容长度必须在10到2000个字符之间', trigger: 'blur' }
  ]
}

// 对话框
const dialog = ref({
  visible: false,
  title: ''
})

// 上传相关
const baseUrl = import.meta.env.VITE_APP_BASE_API
const uploadImgUrl = baseUrl + '/user/forum/upload/image'
const headers = ref({ Authorization: 'Bearer ' + getToken() })

console.log('上传配置:', {
  baseUrl,
  uploadImgUrl,
  headers: headers.value
})

// 获取分类列表
const getCategories = async () => {
  try {
    const res = await listCategory()
    categoryOptions.value = res.rows
  } catch (error) {
    console.error('获取分类失败:', error)
    ElMessage.error('获取分类失败')
  }
}

// 获取帖子列表
const getList = async () => {
  loading.value = true
  try {
    console.log('获取帖子列表前的用户ID:', userId.value)
    const res = await listPost(queryParams.value)
    console.log('获取到的帖子列表:', res)
    postList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleSearch = () => {
  queryParams.value.pageNum = 1
  getList()
}

// 创建帖子
const handleCreate = () => {
  resetForm()
  dialog.value = {
    visible: true,
    title: '发布帖子'
  }
}

// 查看帖子详情
const viewDetail = (postId) => {
  router.push({
    name: 'PostDetail',
    params: { id: postId }
  })
}

// 上传前处理
const beforeUpload = (file) => {
  console.log('上传前检查文件:', file)
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB!')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (response, file) => {
  console.log('上传响应:', response)
  console.log('上传文件:', file)
  
  if (response.code === 200) {
    // 确保 images 数组已初始化
    if (!Array.isArray(form.value.images)) {
      form.value.images = []
    }
    // 从 msg 字段获取图片路径
    const imageUrl = response.msg
    if (imageUrl && !form.value.images.includes(imageUrl)) {
      form.value.images.push(imageUrl)
      console.log('上传成功，当前图片数组:', form.value.images)
    }
  } else {
    console.error('上传失败:', response)
    ElMessage.error(response.msg || '上传失败')
  }
}

// 移除图片
const handleUploadRemove = (file) => {
  console.log('移除文件:', file)
  const fileUrl = file.response?.msg || file.url  // 修改为与上传响应格式一致
  if (fileUrl && Array.isArray(form.value.images)) {
    // 如果是完整URL，需要移除基础路径
    const relativePath = fileUrl.startsWith(baseUrl) ? 
      fileUrl.substring(baseUrl.length) : fileUrl
    const index = form.value.images.indexOf(relativePath)
    if (index > -1) {
      form.value.images.splice(index, 1)
      console.log('移除图片后的数组:', form.value.images)
    }
  }
}

// 取消按钮
const cancel = () => {
  resetForm()
  dialog.value.visible = false
}

// 解析图片数据
const parseImages = (images) => {
  console.log('开始解析图片数据:', images)
  if (!images) {
    console.log('图片数据为空，返回空数组')
    return []
  }
  
  try {
    let imageArray = []
    // 如果是字符串，尝试解析JSON
    if (typeof images === 'string') {
      console.log('尝试解析JSON字符串:', images)
      try {
        imageArray = JSON.parse(images)
        if (!Array.isArray(imageArray)) {
          console.log('解析结果不是数组，重置为空数组')
          return []
        }
      } catch (error) {
        console.error('JSON解析失败:', error)
        return []
      }
    }
    // 如果已经是数组，直接使用
    else if (Array.isArray(images)) {
      imageArray = images
    }
    else {
      console.log('images 既不是字符串也不是数组，返回空数组')
      return []
    }
    
    // 过滤掉无效值并为每个图片URL添加基础路径
    const result = imageArray
      .filter(image => image != null && image !== '' && typeof image === 'string')
      .map(image => {
        if (image.startsWith('http')) {
          return image
        }
        return baseUrl + image
      })
    
    console.log('最终处理的图片数组:', result)
    return result
  } catch (error) {
    console.error('解析图片数据失败:', error)
    return []
  }
}

// 编辑按钮操作
const handleEdit = async (postId) => {
  try {
    console.log('开始获取帖子详情, postId:', postId)
    const res = await getPost(postId)
    console.log('获取帖子详情响应:', res)
    
    if (res.code === 200 && res.data) {
      const postData = res.data
      console.log('原始帖子数据:', postData)
      
      // 先初始化基本数据
      form.value = {
        postId: postData.postId,
        title: postData.title,
        categoryId: postData.categoryId,
        content: postData.content,
        images: []  // 初始化为空数组
      }

      // 重置文件列表
      fileList.value = []

      // 处理图片数据
      if (postData.images) {
        let imageUrls = []
        
        // 尝试解析图片数据
        try {
          if (typeof postData.images === 'string') {
            imageUrls = JSON.parse(postData.images || '[]')
          }
        } catch (error) {
          console.error('解析图片数据失败:', error)
          imageUrls = []
        }

        // 确保imageUrls是数组
        if (!Array.isArray(imageUrls)) {
          imageUrls = []
        }

        // 过滤并处理有效的图片URL
        const validUrls = imageUrls.filter(url => typeof url === 'string' && url.trim() !== '')
        
        if (validUrls.length > 0) {
          // 设置表单的图片数据
          form.value.images = validUrls

          // 构建文件列表
          fileList.value = validUrls.map((url, index) => ({
            uid: index,
            name: `图片${index + 1}`,
            url: url.startsWith('http') ? url : baseUrl + url,
            status: 'success',
            response: { code: 200, msg: url }
          }))
        }
      }

      // 显示对话框
      dialog.value = {
        visible: true,
        title: '编辑帖子'
      }
    } else {
      ElMessage.error(res.msg || '获取帖子详情失败')
    }
  } catch (error) {
    console.error('编辑帖子操作失败:', error)
    ElMessage.error('获取帖子详情失败，请重试')
  }
}

// 提交表单
const submitForm = async () => {
  try {
    const formData = { ...form.value }
    console.log('提交前的表单数据:', formData)
    
    // 处理图片数据
    if (Array.isArray(formData.images)) {
      // 过滤掉所有的无效值
      const validImages = formData.images.filter(img => 
        img != null && img !== undefined && img !== '' && typeof img === 'string'
      )
      console.log('过滤后的有效图片:', validImages)
      
      if (validImages.length > 0) {
        // 确保所有图片都是相对路径
        const processedImages = validImages.map(img => {
          if (img.startsWith(baseUrl)) {
            return img.substring(baseUrl.length)
          }
          return img
        })
        formData.images = JSON.stringify(processedImages)
        console.log('处理后的图片数据:', formData.images)
      } else {
        formData.images = '[]'  // 如果没有有效图片，设置为空数组字符串
      }
    } else {
      formData.images = '[]'  // 如果 images 不是数组，设置为空数组字符串
    }

    console.log('最终提交的表单数据:', formData)

    let res
    if (formData.postId) {
      res = await updatePost(formData)
    } else {
      res = await addPost(formData)
    }

    if (res.code === 200) {
      ElMessage.success(formData.postId ? '修改成功' : '发布成功')
      dialog.value.visible = false
      getList()
    } else {
      ElMessage.error(res.msg || (formData.postId ? '修改失败' : '发布失败'))
    }
  } catch (error) {
    console.error(form.value.postId ? '修改帖子失败:' : '发布帖子失败:', error)
    ElMessage.error(form.value.postId ? '修改失败' : '发布失败')
  }
}

// 表单重置
const resetForm = () => {
  form.value = {
    postId: undefined,
    title: undefined,
    categoryId: undefined,
    content: undefined,
    images: []  // 确保初始化为空数组
  }
  fileList.value = []
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

// 处理头像URL
const getAvatarUrl = (avatar) => {
  if (!avatar) return '/avatar.png'
  if (avatar.startsWith('http')) return avatar
  return import.meta.env.VITE_APP_BASE_API + avatar
}

onMounted(() => {
  // 从 store 中获取用户ID
  userId.value = userStore.userId
  console.log('当前用户ID:', userId.value)
  getCategories()
  getList()
})
</script>

<style lang="scss" scoped>
.user-forum {
  padding: 20px;

  .action-area {
    margin-bottom: 20px;
  }

  .post-list {
    margin-bottom: 20px;

    .post-item {
      margin-bottom: 20px;

      .post-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .user-info {
          display: flex;
          align-items: center;

          .info-text {
            margin-left: 10px;
            display: flex;
            flex-direction: column;

            .username {
              font-weight: bold;
              font-size: 16px;
            }

            .time {
              font-size: 12px;
              color: #999;
            }
          }
        }

        .post-stats {
          display: flex;
          align-items: center;
          gap: 15px;

          .stat-item {
            display: flex;
            align-items: center;
            gap: 5px;
            color: #666;
            font-size: 14px;
          }
        }
      }

      .post-content {
        cursor: pointer;

        .post-title {
          margin: 0 0 10px;
          font-size: 18px;
          font-weight: bold;
        }

        .post-summary {
          margin: 0 0 15px;
          color: #666;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 3;
          -webkit-box-orient: vertical;
        }

        .post-images {
          display: flex;
          gap: 10px;

          .preview-image {
            width: 120px;
            height: 120px;
            border-radius: 4px;
          }
        }
      }
    }
  }

  .pagination-container {
    text-align: center;
    margin-top: 20px;
  }

  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  :deep(.el-upload-list--picture-card .el-upload-list__item) {
    width: 100px;
    height: 100px;
  }

  .post-title-link {
    color: #2c3e50;
    text-decoration: none;
    font-weight: bold;
    
    &:hover {
      color: #409eff;
      text-decoration: underline;
    }
  }
}
</style> 